package com.icez.banner_view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.core.view.marginEnd
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback

/**
 * 广告控件
 * @sample
 * @author Icez
 */
class BannerView @JvmOverloads constructor(
    context: Context, val attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {

    var mIsInfiniteLoop: Boolean = false

    private var mViewPager2: ViewPager2? = null

    private var mAutoLoopTask: AutoLoopTask? = null

    private var mLoopTime = 2000L

    private var mPaddingLeft: Int = 100

    private var mPaddingRight: Int = 100

    // 是否自動循環
    private var mIsAutoLoop: Boolean = true

    // 縮放比例
    private var mAlphaScaleRatio: Float = 0.95f

    private var mDataSize:Int = 0

    // 切換類型
    private var mTransformerType: TransformerType = TransformerType.ALPHA_SCALE

    private var mOnPageListener:OnPageListener ?= null

    private var mOnPageChangeCallback = object:OnPageChangeCallback(){
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            if(mIsInfiniteLoop){
                val index = position%mDataSize
                mOnPageListener?.onPaged(index)
            }else{
                mOnPageListener?.onPaged(position)
            }

        }
    }

    // 适配器里面数据监听
    val mAdapterDataObserver: RecyclerView.AdapterDataObserver = object :
        RecyclerView.AdapterDataObserver() {
        override fun onChanged() {
            super.onChanged()
            if ((mViewPager2?.adapter?.itemCount ?: 0) <= 1) {
                stop()
            } else {
                start()
            }
        }
    }

    init {
        initStyleValue()
        removeAllViews()
        mViewPager2 = ViewPager2(context)

        mAutoLoopTask = AutoLoopTask()
        val viewPager2LayoutParams =
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        mViewPager2?.layoutParams = viewPager2LayoutParams
        mViewPager2?.offscreenPageLimit = 2

        when (mTransformerType) {
            TransformerType.ALPHA_SCALE -> {
                mViewPager2?.clipChildren = false
                mViewPager2?.clipToPadding = false
                mViewPager2?.setPadding(mPaddingLeft, 0, mPaddingRight, 0)
                mViewPager2?.setPageTransformer(AlphaScalePageTransformer(mAlphaScaleRatio))
            }
            TransformerType.LEFT_RIGHT_SPACE -> {
                mViewPager2?.clipChildren = false
                mViewPager2?.clipToPadding = false
                mViewPager2?.setPadding(mPaddingLeft, 0, mPaddingRight, 0)
                mViewPager2?.setPageTransformer(LeftRightSpacePageTransformer(mAlphaScaleRatio))
            }
            TransformerType.COMMON -> {

            }
        }

        val mRecyclerView = mViewPager2?.getChildAt(0) as RecyclerView
        mRecyclerView.overScrollMode = View.OVER_SCROLL_NEVER
        addView(mViewPager2)
    }

    private fun initStyleValue(){
        val mTypedArray = context.obtainStyledAttributes(attrs,R.styleable.BannerView)
        mIsInfiniteLoop = mTypedArray.getBoolean(R.styleable.BannerView_isInfiniteLoop,false)
        mLoopTime = mTypedArray.getInteger(R.styleable.BannerView_loopTime,2000).toLong()
        mPaddingLeft = mTypedArray.getDimensionPixelOffset(R.styleable.BannerView_paddingLeft,100)
        mPaddingRight = mTypedArray.getDimensionPixelOffset(R.styleable.BannerView_paddingRight,100)
        mIsAutoLoop = mTypedArray.getBoolean(R.styleable.BannerView_isAutoLoop,false)
        mAlphaScaleRatio = mTypedArray.getFloat(R.styleable.BannerView_alphaScaleRatio,0.95f)
        val mTransformerTypeIndex = mTypedArray.getInteger(R.styleable.BannerView_bannerType,TransformerType.ALPHA_SCALE.ordinal)

        mTypedArray.recycle()

        when(mTransformerTypeIndex){
            0 -> {
                mTransformerType = TransformerType.COMMON
            }
            1 -> {
                mTransformerType = TransformerType.ALPHA_SCALE
            }
            2 -> {
                mTransformerType = TransformerType.LEFT_RIGHT_SPACE
            }
        }
    }


    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_OUTSIDE -> {
                start()
            }
            MotionEvent.ACTION_DOWN -> {
                stop()
            }
        }
        return super.dispatchTouchEvent(ev)
    }


    // 开始
    fun start() {
        if (mIsAutoLoop && mDataSize > 1) {
            stop()
            postDelayed(mAutoLoopTask, mLoopTime)
        }

    }

    // 停止
    fun stop() {
        removeCallbacks(mAutoLoopTask)
    }

    // 设置适配器
    fun <T, VB : ViewDataBinding> setAdapter(adapter: BannerViewAdapter<T, VB>?,onPageListener:OnPageListener) {
        adapter?.mIsInfiniteLoop = mIsInfiniteLoop
        mViewPager2?.adapter?.registerAdapterDataObserver(mAdapterDataObserver)
        mViewPager2?.adapter = adapter
        mDataSize = adapter?.mData?.size?:0
        mOnPageListener = onPageListener
        if (mIsInfiniteLoop && mDataSize>1) {
            val centerPosition = Int.MAX_VALUE / 2 - Int.MAX_VALUE / 2 % 10
            mViewPager2?.setCurrentItem(centerPosition, false)
        }else{
            mOnPageListener?.onPaged(0)
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        mViewPager2?.registerOnPageChangeCallback(mOnPageChangeCallback)
        start()

    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mViewPager2?.unregisterOnPageChangeCallback(mOnPageChangeCallback)
        stop()
    }

    // 自动遍历
    inner class AutoLoopTask : Runnable {

        override fun run() {
            val count = mViewPager2?.adapter?.itemCount ?: 0
            if (count == 0) {
                return
            }
            val next = ((mViewPager2?.currentItem ?: 0) + 1) % count
            val smoothScroll = next != 0
            if (mIsInfiniteLoop) {
                mViewPager2?.setCurrentItem(next, smoothScroll)
                postDelayed(mAutoLoopTask, mLoopTime)
            } else {
                if (!smoothScroll) {
                    stop()
                } else {
                    mViewPager2?.setCurrentItem(next, smoothScroll)
                    postDelayed(mAutoLoopTask, mLoopTime)
                }
            }

        }

    }


    interface OnPageListener{
        fun onPaged(position:Int)
    }


    enum class TransformerType {
        COMMON,
        ALPHA_SCALE,
        LEFT_RIGHT_SPACE
    }

}